/**
 * AI工具栏组件
 * 提供常用的AI写作和编辑功能
 */

import React, { useState, useCallback } from 'react'
import { useAIWriter, AIAction, AIWriterOptions } from '../../hooks/ai'
import { Button } from '@/components/ui/button'
import {
  Wand2,
  Expand,
  Languages,
  FileText,
  PenTool,
  Sparkles,
  List,
  Search,
  TrendingUp,
  Loader2
} from 'lucide-react'

interface AIToolbarProps {
  selectedText?: string
  onActionComplete?: (result: string) => void
  onActionError?: (error: string) => void
  className?: string
  disabled?: boolean
}

interface ActionItem {
  id: AIAction
  label: string
  icon: React.ComponentType<any>
  description: string
  requiresText?: boolean
  options?: Partial<AIWriterOptions>
}

export const AIToolbar: React.FC<AIToolbarProps> = ({
  selectedText = '',
  onActionComplete,
  onActionError,
  className = '',
  disabled = false,
}) => {
  const [showOptions, setShowOptions] = useState<AIAction | null>(null)
  const [actionOptions, setActionOptions] = useState<AIWriterOptions>({})
  const {
    isLoading,
    currentAction,
    polish,
    expand,
    translate,
    summarize,
    continue: continueWriting,
    generate,
    fixGrammar,
    changeTone,
    formatMarkdown,
    extractKeywords,
    generateOutline,
    improveSEO,
  } = useAIWriter()

  const actions: ActionItem[] = [
    {
      id: 'polish',
      label: '润色',
      icon: Wand2,
      description: '优化表达，提升文本质量',
      requiresText: true,
      options: { style: 'formal' }
    },
    {
      id: 'expand',
      label: '扩写',
      icon: Expand,
      description: '增加细节，丰富内容',
      requiresText: true,
      options: { style: 'creative' }
    },
    {
      id: 'translate',
      label: '翻译',
      icon: Languages,
      description: '翻译到其他语言',
      requiresText: true,
    },
    {
      id: 'summarize',
      label: '摘要',
      icon: FileText,
      description: '生成内容摘要',
      requiresText: true,
    },
    {
      id: 'continue',
      label: '续写',
      icon: PenTool,
      description: '智能续写内容',
      requiresText: true,
    },
    {
      id: 'generate',
      label: '生成',
      icon: Sparkles,
      description: 'AI创作新内容',
      requiresText: false,
    },
    {
      id: 'fixGrammar',
      label: '语法',
      icon: PenTool,
      description: '修正语法错误',
      requiresText: true,
    },
    {
      id: 'changeTone',
      label: '语气',
      icon: TrendingUp,
      description: '调整文本语气',
      requiresText: true,
    },
    {
      id: 'formatMarkdown',
      label: '格式化',
      icon: FileText,
      description: '优化Markdown格式',
      requiresText: true,
    },
    {
      id: 'extractKeywords',
      label: '关键词',
      icon: Search,
      description: '提取核心关键词',
      requiresText: true,
    },
    {
      id: 'generateOutline',
      label: '大纲',
      icon: List,
      description: '生成文档大纲',
      requiresText: false,
    },
    {
      id: 'improveSEO',
      label: 'SEO',
      icon: TrendingUp,
      description: 'SEO优化建议',
      requiresText: true,
    },
  ]

  const handleAction = useCallback(async (action: ActionItem) => {
    if (!action.requiresText && action.id !== 'generate' && action.id !== 'generateOutline') {
      // 这些操作需要选中文本
      if (!selectedText.trim()) {
        onActionError?.('请先选择要处理的文本')
        return
      }
    }

    try {
      let result: string | null = null

      switch (action.id) {
        case 'polish':
          result = await polish(selectedText, action.options)
          break
        case 'expand':
          result = await expand(selectedText, action.options)
          break
        case 'translate':
          const targetLang = actionOptions.language || 'English'
          result = await translate(selectedText, targetLang, action.options)
          break
        case 'summarize':
          result = await summarize(selectedText, action.options)
          break
        case 'continue':
          result = await continueWriting(selectedText, actionOptions.context)
          break
        case 'generate':
          const prompt = actionOptions.context || selectedText || '请输入创作提示'
          result = await generate(prompt, action.options)
          break
        case 'fixGrammar':
          result = await fixGrammar(selectedText, action.options)
          break
        case 'changeTone':
          const tone = actionOptions.tone || 'professional'
          result = await changeTone(selectedText, tone, action.options)
          break
        case 'formatMarkdown':
          result = await formatMarkdown(selectedText)
          break
        case 'extractKeywords':
          const keywords = await extractKeywords(selectedText)
          result = keywords
          break
        case 'generateOutline':
          const topic = actionOptions.context || selectedText || '请输入主题'
          result = await generateOutline(topic, action.options)
          break
        case 'improveSEO':
          result = await improveSEO(selectedText)
          break
        default:
          throw new Error(`Unsupported action: ${action.id}`)
      }

      if (result) {
        onActionComplete?.(result)
      } else {
        onActionError?.('AI处理未返回结果')
      }

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '处理失败'
      onActionError?.(errorMessage)
    }
  }, [
    selectedText,
    actionOptions,
    polish,
    expand,
    translate,
    summarize,
    continueWriting,
    generate,
    fixGrammar,
    changeTone,
    formatMarkdown,
    extractKeywords,
    generateOutline,
    improveSEO,
    onActionComplete,
    onActionError,
  ])

  const handleActionWithOptions = useCallback((action: ActionItem) => {
    if (action.id === 'translate') {
      setShowOptions(action.id)
    } else if (action.id === 'changeTone') {
      setShowOptions(action.id)
    } else if (action.id === 'generate' || action.id === 'generateOutline') {
      setShowOptions(action.id)
    } else if (action.id === 'continue') {
      setShowOptions(action.id)
    } else {
      handleAction(action)
    }
  }, [handleAction])

  const handleOptionsConfirm = useCallback(() => {
    const action = actions.find(a => a.id === showOptions)
    if (action) {
      handleAction(action)
    }
    setShowOptions(null)
  }, [showOptions, actions, handleAction])

  const filteredActions = actions.filter(action =>
    !disabled && (!action.requiresText || selectedText.trim())
  )

  return (
    <div className={`ai-toolbar bg-white border border-gray-200 rounded-lg shadow-sm ${className}`}>
      {/* 选项弹窗 */}
      {showOptions && (
        <div className="absolute top-full left-0 mt-2 p-4 bg-white border border-gray-200 rounded-lg shadow-lg z-50 min-w-80">
          <h3 className="font-medium mb-3">
            {actions.find(a => a.id === showOptions)?.label}选项
          </h3>

          {showOptions === 'translate' && (
            <div className="space-y-3">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  目标语言
                </label>
                <select
                  value={actionOptions.language || 'English'}
                  onChange={(e) => setActionOptions(prev => ({ ...prev, language: e.target.value }))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="English">英语</option>
                  <option value="Chinese">中文</option>
                  <option value="Japanese">日语</option>
                  <option value="Korean">韩语</option>
                  <option value="French">法语</option>
                  <option value="German">德语</option>
                  <option value="Spanish">西班牙语</option>
                </select>
              </div>
            </div>
          )}

          {showOptions === 'changeTone' && (
            <div className="space-y-3">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  目标语气
                </label>
                <select
                  value={actionOptions.tone || 'neutral'}
                  onChange={(e) => setActionOptions(prev => ({ ...prev, tone: e.target.value as AIWriterOptions['tone'] }))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                >
                  <option value="neutral">中性</option>
                  <option value="positive">积极</option>
                  <option value="negative">消极</option>
                  <option value="persuasive">说服性</option>
                  <option value="informative">信息性</option>
                </select>
              </div>
            </div>
          )}

          {showOptions === 'generate' && (
            <div className="space-y-3">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  创作提示
                </label>
                <textarea
                  value={actionOptions.context || ''}
                  onChange={(e) => setActionOptions(prev => ({ ...prev, context: e.target.value }))}
                  placeholder="请输入创作提示或主题..."
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  rows={3}
                />
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">风格</label>
                  <select
                    value={actionOptions.style || 'creative'}
                    onChange={(e) => setActionOptions(prev => ({ ...prev, style: e.target.value as AIWriterOptions['style'] }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="creative">创意</option>
                    <option value="formal">正式</option>
                    <option value="casual">随意</option>
                    <option value="academic">学术</option>
                    <option value="technical">技术</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">长度</label>
                  <select
                    value={actionOptions.length || 'medium'}
                    onChange={(e) => setActionOptions(prev => ({ ...prev, length: e.target.value as AIWriterOptions['length'] }))}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="short">简短</option>
                    <option value="medium">中等</option>
                    <option value="long">较长</option>
                  </select>
                </div>
              </div>
            </div>
          )}

          {showOptions === 'continue' && (
            <div className="space-y-3">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  续写上下文
                </label>
                <textarea
                  value={actionOptions.context || ''}
                  onChange={(e) => setActionOptions(prev => ({ ...prev, context: e.target.value }))}
                  placeholder="提供续写的上下文信息..."
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  rows={2}
                />
              </div>
            </div>
          )}

          {showOptions === 'generateOutline' && (
            <div className="space-y-3">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  主题或标题
                </label>
                <input
                  type="text"
                  value={actionOptions.context || ''}
                  onChange={(e) => setActionOptions(prev => ({ ...prev, context: e.target.value }))}
                  placeholder="请输入主题或标题..."
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>
            </div>
          )}

          <div className="flex justify-end space-x-2 mt-4">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setShowOptions(null)}
            >
              取消
            </Button>
            <Button
              size="sm"
              onClick={handleOptionsConfirm}
            >
              确认
            </Button>
          </div>
        </div>
      )}

      {/* 主工具栏 */}
      <div className="flex items-center p-2">
        <div className="flex items-center space-x-1 mr-4">
          <div className="w-2 h-2 bg-green-500 rounded-full"></div>
          <span className="text-sm text-gray-600">AI助手</span>
        </div>

        <div className="flex items-center space-x-1">
          {filteredActions.map((action) => {
            const Icon = action.icon
            return (
              <Button
                key={action.id}
                variant="ghost"
                size="sm"
                onClick={() => handleActionWithOptions(action)}
                disabled={isLoading}
                title={action.description}
                className="h-8 w-8 p-0"
              >
                {isLoading && currentAction === action.id ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  <Icon className="h-4 w-4" />
                )}
              </Button>
            )
          })}
        </div>

        {selectedText && (
          <div className="ml-4 text-sm text-gray-500">
            已选择 {selectedText.length} 字符
          </div>
        )}
      </div>

      {/* 加载状态 */}
      {isLoading && (
        <div className="border-t border-gray-200 px-4 py-2 bg-gray-50">
          <div className="flex items-center space-x-2">
            <Loader2 className="h-4 w-4 animate-spin text-blue-500" />
            <span className="text-sm text-gray-600">
              {currentAction ? `正在${currentAction}...` : 'AI处理中...'}
            </span>
          </div>
        </div>
      )}
    </div>
  )
}